//
//  RMSecondViewController.m
//  rmplanner
//
//  Created by Andrew Pigram on 2/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMSecondViewController.h"
#import "RMDetailViewController.h"
#import "RMParser.h"
#import "RMMeal.h"
#import "RMTabBarController.h"

@interface RMSecondViewController ()

@property (strong, nonatomic) UIAlertView* alertView;
@property (strong, nonatomic) UIActivityIndicatorView* indicator;

@end

@implementation RMSecondViewController

static int selectedRow;

@synthesize meals, mealData, mealList, dateLabel, counts, dates, indicator, alertView;

#pragma mark UITableViewController functions

- (void)viewWillAppear:(BOOL)animated
{
	// connect to the server to download the meal data
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/futureMeals"];
	NSURLRequest* request = [NSURLRequest requestWithURL:url];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSAssert((connection != nil), @"Could not connect");
	
	// display the loading alert
	alertView = [[UIAlertView alloc] init];
	alertView.title = @"Loading";
	alertView.frame = CGRectMake(110, 20, 50, 50);
	indicator = [[UIActivityIndicatorView alloc] init];
	indicator.frame = CGRectMake(120, 45, 40, 40);
	[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[alertView addSubview:indicator];
	[alertView show];
	[indicator startAnimating];
	
	meals = [[NSMutableArray alloc] init];
}

// perform initial loading and XML parsing
- (void)viewDidLoad
{
    [super viewDidLoad];
	
	self.navigationItem.title = @"Future Meals";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

// lock device orientations
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
	    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
	} else {
	    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
	}
}

#pragma mark UITableViewController datasource/delegate functions

// populate each cell with its respective data
- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	// create a closed cell
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ClosedCell"];
	cell.textLabel.text = [dates objectAtIndex:indexPath.row];
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
	{
		selectedRow = indexPath.row;
		[self performSegueWithIdentifier:@"Details" sender:self];
	}
	else
	{
		RMDetailViewController* controller = [[[self splitViewController] viewControllers] objectAtIndex:1];
		NSString* date = [self tableView:self.tableView cellForRowAtIndexPath:indexPath].textLabel.text;
		[controller setDetailItems:[meals objectAtIndex:indexPath.row] withDate:date];
	}
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return [meals count];
}

#pragma mark Segue functions
// only run on the iPad
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"Details"])
	{
		// set the details of the destination view controller
		RMDetailViewController* controller = [segue destinationViewController];
		NSString* date = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0]].textLabel.text;
		[controller setDetailItems:[meals objectAtIndex:selectedRow] withDate:date];
    }
}

#pragma mark NSURLConnection delegate functions

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// initialise the data container
	mealData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// append the newly downloaded data
	[mealData appendData:data];
}

// begin the parsing operation when the URL has completely loaded
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// nullify the connection and turn off the activity indicator
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	connection = nil;
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	NSString* data = [[NSString alloc] initWithData:mealData encoding:NSUTF8StringEncoding];
	
	NSLog(@"%@", data);
	
	// begin parsing
	RMParser* parser = [[RMParser alloc] init];
	[parser setData:mealData sender:self];
	[parser start];
	
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
	{
		RMDetailViewController* controller = [[[self splitViewController] viewControllers] objectAtIndex:1];
		
		if ([meals count] > 0)
		{
			[controller setDetailItems:[meals objectAtIndex:0] withDate:nil];
			[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
		}
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
}

#pragma mark Interface Builder actions

- (IBAction)logout
{
	[self dismissModalViewControllerAnimated:YES];
}

@end
